<script setup lang="ts">
import { RouterView, useRoute } from 'vue-router';
import { useWebsocketStore } from '@/store/websocket';
import { onBeforeUnmount, onMounted, watch } from 'vue';
import { getIsLogin, getLoginUserId } from './utils/storage';
import { parseStringToObject } from './utils/parse';
import { SIGNAL_TYPE_ONE_TO_ONE, SIGNAL_TYPE_SYSTEM } from './constants/constants';
import { useNoticeStore } from './store/nitice';
import { ElNotification } from 'element-plus';
import "quill/dist/quill.core.css";
const websocketStore = useWebsocketStore();
const route = useRoute();
let isNotConnect = true;
watch(
  () => route.name,
  (curRouteName) => {
    const isLogin: boolean = getIsLogin();
    // 只有已登录、未连接、且当前路由不是双人会议这种会自己创建连接的页面中，才创建连接
    // 如果当前页面是公告详情这种，也无需创建连接
    if (
      isLogin &&
      curRouteName !== 'singleMeeting' &&
      curRouteName !== 'noticeDetail' &&
      isNotConnect
    ) {
      isNotConnect = false;
      const websocket: WebSocket = websocketStore.connect();
      websocket.addEventListener('message', onMessage);
    }
  }
);
function onMessage(event: MessageEvent) {
  const jsonMsg = parseStringToObject(event.data);
  if (jsonMsg.cmd === SIGNAL_TYPE_SYSTEM) {
    // 如果是SIGNAL_TYPE_SYSTEM，则需要再对msg进行反序列化
    jsonMsg.msg = parseStringToObject(jsonMsg.msg);
  }
  console.log(jsonMsg);
  const cmd = jsonMsg.cmd;
  switch (cmd) {
    case SIGNAL_TYPE_SYSTEM:
      handleSystemMessage(jsonMsg);
      break;
    case SIGNAL_TYPE_ONE_TO_ONE:
      handleOneToOneMessage(jsonMsg);
      break;
  }
}
const noticeStore = useNoticeStore();
// 推荐成果或需求
function handleSystemMessage(msg: any) {
  noticeStore.setHasNotice(true);
  noticeStore.noticeList.unshift(msg);
  // 当type等于1时，发布的是需求，推送的是成果
  ElNotification({
    title: '系统提示',
    message: `您发布了一条${msg.msg.type === 1 ? '需求' : '成果'}，系统根据已有${
      msg.msg.type === 1 ? '成果' : '需求'
    }给您进行了推送，点击头部消息通知图标可查看！`,
    type: 'success',
  });
}
// 接收到别人的消息的回调
function handleOneToOneMessage(msg: any) {
  // 如果是自己发消息给别人，或者是当前已在聊天界面中，则不需要将其作为提醒
  const curRouteName = route.name;
  if (msg.remoteUid * 1 === getLoginUserId() || curRouteName === 'chat') {
    return;
  }

  noticeStore.setHasNotice(true);
  noticeStore.noticeList.unshift(msg);
}
onMounted(() => {
  window.addEventListener('beforeunload', websocketStore.close);
});
onBeforeUnmount(() => {
  window.removeEventListener('beforeunload', websocketStore.close);
});
</script>

<template>
  <RouterView />
</template>

<style lang="scss">
</style>
